//index.js
const config = require('../../conf.js');
const util = require('../../utils/util.js');
const request = require('../../utils/request.js');

var curPage = 1;
var app = getApp();
Page({
  data: {
      showLoading: false,
      loadingMessage: '',
      showToast: false,
      toastMessage: '',
      imgList: [],
      layoutList: [],
      layoutColumnSize: 3,
      previewing: false,
      duration:0,
      previewIndex: 0,
      showingActionsSheet: false,
      inActionImgUrl: '',
      navItems: [],
      navBtnSelectIdx: 0,
      page: 1,
      imgType:1,
      mid: '',
      hasMore: true,
      scrollTop: 1,
      showLoadMore: false
  },
  showLoading(message) {
      this.setData({ showLoading: true, loadingMessage: message });
  },
  hideLoading() {
      this.setData({ showLoading: false, loadingMessage: '' });
  },
  showToast(toastMessage) {
      this.setData({ showToast: true, toastMessage });
  },
  hideToast() {
      this.setData({ showToast: false, toastMessage: '' });
  },
  renderImgList() {
      console.log('render')
      let layoutColumnSize = this.data.layoutColumnSize;
      let layoutList = [];
      console.log(this.data.imgList)
      if (this.data.imgList.length) {
        console.log('render2')
          layoutList = util.matrixArr((this.data.imgList), layoutColumnSize);
          console.log(layoutList)
          let lastRow = layoutList[layoutList.length - 1];
          if (lastRow.length < layoutColumnSize) {
              let supplement = Array(layoutColumnSize - lastRow.length).fill(0);
              lastRow.push(...supplement);
          }
      }
      this.setData({ layoutList });
  },
  fetchTags() {
      wx.showNavigationBarLoading();
      var that = this;
      wx.request({
        url: "https://route.showapi.com/1208-1",
        data: {
          'showapi_appid':app.globalData.appid,
          'showapi_sign':app.globalData.apiKey,
          'page':curPage.toString()
        },
        method: 'GET',
        success: function(res){
          // success
          if(curPage == 1)
            that.setData(
              { navItems:res.data.showapi_res_body.data }
            );
          else
            that.setData(
              { navItems: that.data.navItems.concat(res.data.showapi_res_body.data) }
            );
  
          curPage = curPage + 1;
          wx.hideNavigationBarLoading();
          if (that.data.isPullDownRefreshing)
            wx.stopPullDownRefresh();
          if (that.data.isPullDownRefreshing)
            that.setData({ isPullDownRefreshing: false })
          if (that.data.isHideLoadMore)  
            that.setData({ isHideLoadMore: false })
        },
        fail: function() {
          // fail
        },
        complete: function() {
          // complete
        }
      })
  },
  fetchImgs(cid) {
      if(!this.data.imgList.length){
          this.showLoading('loading...'); // 如果是第一次加载请求图片,就显示loading转
      }
    //   return request({ method: 'GET', url: util.getUrl('/girls', [{c:!util.isEmpty(cid)?cid:'xinggan'}, {p:this.data.page}, {m: this.data.mid}])});

    wx.showNavigationBarLoading();
      var that = this;
      wx.request({
        url: "https://route.showapi.com/1208-2",
        data: {
          'showapi_appid':app.globalData.appid,
          'showapi_sign':app.globalData.apiKey,
          'type':this.data.imgType,
          'page':curPage.toString(),
          'rows':21
        },
        method: 'GET',
        success: function(res){
          // success
          if(curPage == 1)
            that.setData(
              { imgList:res.data.showapi_res_body.data }
            );
          else
            that.setData(
              { imgList: that.data.imgList.concat(res.data.showapi_res_body.data) }
            );
  
            let layoutColumnSize = that.data.layoutColumnSize;
            let layoutList = [];
            console.log(that.data.imgList)
            if (that.data.imgList.length) {
                console.log('render2')
                layoutList = util.matrixArr((that.data.imgList), layoutColumnSize);
                console.log(layoutList)
                let lastRow = layoutList[layoutList.length - 1];
                if (lastRow.length < layoutColumnSize) {
                    let supplement = Array(layoutColumnSize - lastRow.length).fill(0);
                    lastRow.push(...supplement);
                }
            }
            that.setData({ layoutList });

          curPage = curPage + 1;
          wx.hideNavigationBarLoading();
          if (that.data.isPullDownRefreshing)
            wx.stopPullDownRefresh();
        //   if (that.data.isPullDownRefreshing)
        //     that.setData({ isPullDownRefreshing: false })
          if (that.data.showLoadMore){
              that.setData({ showLoadMore: false })
          }  
        console.log(that.data.imgList)
        },
        fail: function() {
          // fail
        },
        complete: function() {
          // complete
          console.log('complete')
          that.hideLoading();
        }
      })
  },
  onReachBottom:function () {
    console.log("reach to bottom...");
    var that = this;
    // that.data.showLoadMore = true;
    this.setData( {
        showLoadMore: true,
    });
    this.fetchImgs();
  },
  showPreview(event) {
      if (this.data.showActionsSheet) {
          return;
      }
      let index = event.target.dataset.index;
      if (index > this.data.imgList.length - 1) {
          return;
      }
      let previewIndex = this.data.imgList[index];
      this.setData({ previewing: true, previewIndex: index ,duration:300});
  },
  dismissPreview() {
      if (this.data.showingActionsSheet) {
          return;
      }
      this.setData({ previewing: false, previewIndex: 0 ,duration:0});
  },
  dismissActionSheet() {
      this.setData({ showingActionsSheet: false, inActionImgUrl: '' });
  },
  showActionSheet(event) {
      this.setData({ showingActionsSheet: true, inActionImgUrl: event.target.dataset.largesrc });
  },
  saveImage() {
      this.showLoading('saving image...');
      console.log('download_image_url', this.data.inActionImgUrl);

      wx.downloadFile({
          url: this.data.inActionImgUrl,
          type: 'image',
          success: (resp) => {
              wx.saveFile({
                  tempFilePath: resp.tempFilePath,
                  success: (resp) => {
                      this.showToast('save successfully...');
                  },
                  fail: (resp) => {
                      console.log('failed to save, try again...', resp);
                  },
                  complete: (resp) => {
                      console.log('complete', resp);
                      this.hideLoading();
                  },
              });
          },

          fail: (resp) => {
              console.log('fail', resp);
          },
      });
      this.setData({ showingActionsSheet: false, inActionImgUrl: '' });
  },
  scroll(e) {
      this.setData({ scrollTop: e.detail.scrollTop});
  },
  goTop: function (e) {  // 一键回到顶部
    if (wx.pageScrollTo) {
       wx.pageScrollTo({
         scrollTop: 0,
         duration: 0
       })
     } else {
       wx.showModal({
         title: '提示',
         content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
       })
     }
   },
  navItemTap(e){
      this.setData({
          scrollTop: -39,
      });
      this.goTop();
      let index = e.target.dataset.index;
      let id = e.target.dataset.id;
      if (index != this.navBtnSelectIdx) {
          curPage = 1;
          this.setData({navBtnSelectIdx: index, mid: '',imgType:id,imgList:[]});
          this.fetchImgs();
      }
  },
//   imgRespHandler(resp, flush) {
//       this.hideLoading();
//       if (resp.code != 0) {
//           this.showToast('load failed, try again...');
//           this.setData({page: this.data.page--});
//           return;
//       }
//       if (util.isEmpty(resp.data)) {
//           this.setData({hasMore: false});
//           this.showToast('all loaded...');
//           this.setData({page: this.data.page--});
//           return;
//       }
//       this.showToast('load successfully');
//       for (var index in resp.data) {
//           resp.data[index].largeSrc = util.imgUrlFix(resp.data[index].largeSrc);
//           resp.data[index].thumbSrc = util.imgUrlFix(resp.data[index].thumbSrc);
//           resp.data[index].smallSrc = util.imgUrlFix(resp.data[index].smallSrc);
//       }
//       this.setData({ 'imgList': flush ? resp.data : this.data.imgList.concat(resp.data), 'mid': resp.mid });
//       this.renderImgList();
//   },
//   onPullDownRefresh() {
//       this.loadImgData(true);
//   },
//   loadMoreEvent() {
//       this.setData( {
//           showLoadMore: true,
//           page: this.data.page + 1
//       });
//       this.loadImgData(false);
//   },
//   loadImgData(flush) {
//       var cid;
//       if (!util.isEmpty(this.data.navItems)) {
//           cid = this.data.navItems[this.data.navBtnSelectIdx].cid;
//       }
//       this.fetchImgs(cid).then((resp) => {
//           this.imgRespHandler(resp, flush);
//       });
//   },
  loadTagData() {
      this.fetchTags().then((resp) => {
          this.hideLoading();
          if (resp.code !== 0) {
              this.showToast('load failed, try again...');
              return;
          }
          this.setData({'navItems': resp.data});
      });
  },
  onLoad() {
    //   this.loadTagData();
    //   this.loadImgData();
    this.fetchTags();
    this.fetchImgs();
    // this.renderImgList();
  }
})
